/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.saver.modules.sys.service;

import com.google.code.kaptcha.Producer;

import com.saver.common.exception.DefaultException;
import com.saver.modules.sys.dao.SysCaptchaDao;
import com.saver.modules.sys.entity.SysCaptchaEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Optional;

/**
 * 验证码
 *
 * @author yuxiaolong
 * @email 1005471232@qq.com
 * @date 2018年08月30日 下午10:45
 */
@Service
public class SysCaptchaService {

    @Autowired
    private Producer producer;

    @Autowired
    private SysCaptchaDao sysCaptchaDao;

    /**
     * 根据uuid获取验证码
     *
     * @param uuid
     * @return
     */
    public BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new DefaultException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

        SysCaptchaEntity captchaEntity = new SysCaptchaEntity();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(com.saver.common.utils.DateUtils.addDateMinutes(new Date(), 5));
        sysCaptchaDao.save(captchaEntity);

        return producer.createImage(code);
    }

    /**
     * 验证验证码输入是否正确
     *
     * @param uuid uuid
     * @param code 验证码
     * @return
     */
    public boolean validate(String uuid, String code) {
        Optional<SysCaptchaEntity> byId = sysCaptchaDao.findById(uuid);
        if (!byId.isPresent()) {
            return false;
        }

        //删除验证码
        sysCaptchaDao.deleteById(uuid);
        SysCaptchaEntity captchaEntity = byId.get();
        if (captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()) {
            return true;
        }

        return false;
    }
}
